package com.koron.common.web.service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.koron.common.web.bean.DepartmentBean;
import com.koron.common.web.bean.OrgBean;
import com.koron.common.web.bean.StaffBean;
import com.koron.common.web.bean.StaffDepartmentRelationBean;
import com.koron.common.web.mapper.DepartmentMapper;
import com.koron.common.web.mapper.OrgMapper;
import com.koron.common.web.mapper.StaffDepartmentRelationMapper;
import com.koron.common.web.mapper.StaffMapper;
import com.koron.css2.ApplicationConfig;
import com.koron.css2.common.utils.HttpUtils;
import com.koron.util.Constant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.ADOConnection;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.SqlTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@Service("new")
public class NewSynchronizationOrgService implements ISynchronizationOrgService{
	
	private static final Logger LOG = LogManager.getLogger(NewSynchronizationOrgService.class);

	@Value("${app.syn_org_url}")
	private String synOrgUrl;
	
	@Value("${app.syn_department_url}")
	private String synDepartmentUrl;
	
	@Value("${app.syn_staff_url}")
	private String synStaffUrl;
	
	@Value("${app.syn_staff_department_url}")
	private String synStaffDepartmentUrl;
	
	@Override
	public MessageBean<?> synchronization(SessionFactory factory) {
		try {
			return ADOConnection.runTask(new SqlTask() {
				@Override
				public Object run(SessionFactory factory) {
					synOrg(factory);          // 插入组织机构
					synDepartment(factory);  // 插入部门
    				synStaff(factory);       //插入员工
    				synStaffDepartmentRelation(factory); // 插入部门与人员的关系
					return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "执行成功", Void.class);
				}
			}, MessageBean.class);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("组织架构同步失败!!!!!!!" + e);
		}
		return MessageBean.create(-1, "执行失败", Void.class);
	}
	
	@Override
	public MessageBean<?> synDepartment(SessionFactory factory) {
		boolean isTrue = initDepartment(factory);
		if(isTrue) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
			param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
			param.put("pageSize", "-1");
			String data = HttpUtils.sendPostForm(synDepartmentUrl, param);
			JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
			if(jsonObject.get("code").getAsInt() != 0) {
				return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "调用统一用户平台接口失败", Void.class);
			}
			jsonObject = jsonObject.get("data").getAsJsonObject();
			JsonArray jsonArray = jsonObject.get("list").getAsJsonArray();
			Iterator<JsonElement> iterator = jsonArray.iterator();
			List<DepartmentBean> deparmentList = new ArrayList<DepartmentBean>();
			while(iterator.hasNext()) {
				JsonElement json = iterator.next();
				deparmentList.add(newDepartment(json));
			}
			if(deparmentList != null && deparmentList.size() > 0) {
				batchInsertDepartment(factory, deparmentList);
			}
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步组织部门成功", Void.class);
		}
		return MessageBean.create(Constant.MESSAGE_INT_FAIL, "同步组织部门失败", Void.class);
	}
	
	@Override
	public MessageBean<?> synOrg(SessionFactory factory) {
		boolean isTrue = initOrg(factory);
		if(isTrue) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
			param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
			param.put("pageSize", "-1");
			String data = HttpUtils.sendPostForm(synOrgUrl, param);
			JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
			if(jsonObject.get("code").getAsInt() != 0) {
				return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "调用统一用户平台接口失败", Void.class);
			}
			JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();
			Iterator<JsonElement> iterator = jsonArray.iterator();
			List<OrgBean> deparmentList = new ArrayList<OrgBean>();
			while(iterator.hasNext()) {
				JsonElement json = iterator.next();
				deparmentList.add(newOrg(json));
			}
			if(deparmentList != null && deparmentList.size() > 0) {
				batchInsertOrg(factory, deparmentList);
			}
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步组织架构成功", Void.class);
		}
		return MessageBean.create(Constant.MESSAGE_INT_FAIL, "同步组织架构失败", Void.class);
	}

	@Override
	public MessageBean<?> synStaff(SessionFactory factory) {
		boolean isTrue = initStaff(factory);
		if(isTrue) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
			param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
			param.put("pageSize", "-1");
			String data = HttpUtils.sendPostForm(synStaffUrl, param);
			JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
			if(jsonObject.get("code").getAsInt() != 0) {
				return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "调用统一用户平台接口失败", Void.class);
			}
			jsonObject = jsonObject.get("data").getAsJsonObject();
			JsonArray jsonArray = jsonObject.get("list").getAsJsonArray();
			Iterator<JsonElement> iterator = jsonArray.iterator();
			List<StaffBean> staffSize = new ArrayList<StaffBean>();
			while(iterator.hasNext()) {
				JsonElement json = iterator.next();
				staffSize.add(newStaff(json));
			}
			LOG.info("员工数量：{}", staffSize.size());
			if(staffSize != null && staffSize.size() > 0) {
				batchInsertStaff(factory, staffSize);
			}
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步职员成功", Void.class);
		}
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步职员成功", Void.class);
	}
	
	@Override
	public MessageBean<?> synStaffDepartmentRelation(SessionFactory factory) {
		boolean isTrue = initStaffDepartment(factory);
		if(isTrue) {
			Map<String, String> param = new HashMap<String, String>();
			param.put("accessAppCode", ApplicationConfig.getAuthorityAppCode());
			param.put("accessAppSecret", ApplicationConfig.getAuthorityPublicKey());
			param.put("pageSize", "-1");
			String data = HttpUtils.sendPostForm(synStaffDepartmentUrl, param);
			JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
			if(jsonObject.get("code").getAsInt() != 0) {
				return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "调用统一用户平台接口失败", Void.class);
			}
			JsonArray jsonArray = jsonObject.get("data").getAsJsonArray();
			Iterator<JsonElement> iterator = jsonArray.iterator();
			List<StaffDepartmentRelationBean> staffSize = new ArrayList<StaffDepartmentRelationBean>();
			while(iterator.hasNext()) {
				JsonElement json = iterator.next();
				staffSize.add(newStaffDepartment(json));
			}
			LOG.info("员工部门关系数量：{}", staffSize.size());
			if(staffSize != null && staffSize.size() > 0) {
				batchInsertStaffDepartment(factory, staffSize);
			}
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步员工部门成功", Void.class);
		}
		return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "同步员工部门成功", Void.class);
	}
	
	private boolean initStaffDepartment(SessionFactory factory) {
		StaffDepartmentRelationMapper mapper = factory.getMapper(StaffDepartmentRelationMapper.class);
		int iCount = mapper.deleteAll();
		if(iCount > 0) {
			LOG.info("删除组织人员部门关系表成功：{}", iCount);
			return true;
		}
		return false;
	}
	
	private boolean initDepartment(SessionFactory factory) {
		DepartmentMapper mapper = factory.getMapper(DepartmentMapper.class);
		int iCount = mapper.deleteAll();
		if(iCount > 0) {
			LOG.info("删除组织架构成功：{}", iCount);
			return true;
		}
		return false;
	}
	
	private boolean initOrg(SessionFactory factory) {
		OrgMapper mapper = factory.getMapper(OrgMapper.class);
		int iCount = mapper.deleteAll();
		if(iCount > 0) {
			LOG.info("删除组织架构成功：{}", iCount);
			return true;
		}
		return false;
	}
	
	private boolean initStaff(SessionFactory factory) {
		StaffMapper mapper = factory.getMapper(StaffMapper.class);
		int iCount = mapper.deleteAll();
		if(iCount > 0) {
			LOG.info("删除员工信息成功：{}", iCount);
			return true;
		}
		return false;
	}
	
	private void batchInsertDepartment(SessionFactory factory, List<DepartmentBean> deparmentList) {
		DepartmentMapper mapper = factory.getMapper(DepartmentMapper.class);
		int iCount = mapper.batchInsertDepartment(deparmentList);
		if(iCount > 0) {
			LOG.info("组织架构同步成功：{}", iCount);
		}
	}
	private void batchInsertOrg(SessionFactory factory, List<OrgBean> deparmentList) {
		OrgMapper mapper = factory.getMapper(OrgMapper.class);
		int iCount = mapper.batchInsertOrg(deparmentList);
		if(iCount > 0) {
			LOG.info("组织架构同步成功：{}", iCount);
		}
	}
	
	private void batchInsertStaff(SessionFactory factory, List<StaffBean> staffList) {
		StaffMapper mapper = factory.getMapper(StaffMapper.class);
		if(staffList.size() <= BATCH_COUNT) {
			int iCount = mapper.batchInsertStaff(staffList);
			if(iCount > 0) {
				LOG.info("员工信息同步成功：{}", iCount);
			}
		} else {
			int size = staffList.size() / BATCH_COUNT;
			int remainder = staffList.size() % BATCH_COUNT;
			for(int i = 0; i < size; i++) {
				int fromIndex = i * BATCH_COUNT;
				int toIndex = (i + 1) * BATCH_COUNT;
				if((i + 1) == size && remainder > 0) {
					toIndex = toIndex + remainder;
				}
				int iCount = mapper.batchInsertStaff(staffList.subList(fromIndex, toIndex));
				if(iCount > 0) {
					LOG.info("员工信息同步成功：{}", iCount);
				}
			}
		}
	}
	
	private void batchInsertStaffDepartment(SessionFactory factory, List<StaffDepartmentRelationBean> staffList) {
		StaffDepartmentRelationMapper mapper = factory.getMapper(StaffDepartmentRelationMapper.class);
		if(staffList.size() <= BATCH_COUNT) {
			int iCount = mapper.batchInsertStaffDepartment(staffList);
			if(iCount > 0) {
				LOG.info("员工信息同步成功：{}", iCount);
			}
		} else {
			int size = staffList.size() / BATCH_COUNT;
			int remainder = staffList.size() % BATCH_COUNT;
			for(int i = 0; i < size; i++) {
				int fromIndex = i * BATCH_COUNT;
				int toIndex = (i + 1) * BATCH_COUNT;
				if((i + 1) == size && remainder > 0) {
					toIndex = toIndex + remainder;
				}
				int iCount = mapper.batchInsertStaffDepartment(staffList.subList(fromIndex, toIndex));
				if(iCount > 0) {
					LOG.info("员工部门关系信息同步成功：{}", iCount);
				}
			}
		}
	}
	
	private StaffDepartmentRelationBean newStaffDepartment(JsonElement jsonElement) {
		StaffDepartmentRelationBean staffDepartment = new StaffDepartmentRelationBean();
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		if(jsonObject.get("userCode") != null) {
			staffDepartment.setUserCode(jsonObject.get("userCode").getAsString());
		}
		if(jsonObject.get("departmentCode") != null) {
			staffDepartment.setDepartmentCode(jsonObject.get("departmentCode").getAsString());
		}
		return staffDepartment;
	}
	
	private OrgBean newOrg(JsonElement jsonElement) {
		OrgBean department = new OrgBean();
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		if(!jsonObject.get("name").isJsonNull()) {
			department.setName(jsonObject.get("name").getAsString());
		}
		if(!jsonObject.get("namePath").isJsonNull()) {
			department.setDescription(jsonObject.get("namePath").getAsString());
		}
		if(!jsonObject.get("orgKind").isJsonNull()) {
			department.setFlag(jsonObject.get("orgKind").getAsInt());
		}
		if(!jsonObject.get("shortName").isJsonNull()) {
			department.setShortName(jsonObject.get("shortName").getAsString());
		}
		if(!jsonObject.get("sort").isJsonNull()) {
			department.setSort(jsonObject.get("sort").getAsInt());
		}
		if(!jsonObject.get("status").isJsonNull()) {
			department.setStatus(jsonObject.get("status").getAsInt() == 1 ? 0 : 1);
		}
		if(!jsonObject.get("classCode").isJsonNull()) {
			department.setClassCode(jsonObject.get("classCode").getAsString());
		}
		if(!jsonObject.get("code").isJsonNull()) {
			department.setCode(jsonObject.get("code").getAsString());
		}
		if(!jsonObject.get("parentCode").isJsonNull()) {
			department.setParentCode(jsonObject.get("parentCode").getAsString());
		}
		return department;
	}
	
	private DepartmentBean newDepartment(JsonElement jsonElement) {
		DepartmentBean department = new DepartmentBean();
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		if(!jsonObject.get("name").isJsonNull()) {
			department.setName(jsonObject.get("name").getAsString());
		}
		if(!jsonObject.get("namePath").isJsonNull()) {
			department.setDescription(jsonObject.get("namePath").getAsString());
		}
		if(!jsonObject.get("orgKind").isJsonNull()) {
			department.setFlag(jsonObject.get("orgKind").getAsInt());
		}
		if(!jsonObject.get("shortName").isJsonNull()) {
			department.setShortname(jsonObject.get("shortName").getAsString());
		}
		if(!jsonObject.get("sort").isJsonNull()) {
			department.setSn(jsonObject.get("sort").getAsInt());
		}
		if(!jsonObject.get("status").isJsonNull()) {
			department.setState(jsonObject.get("status").getAsInt() == 1 ? 0 : 1);
		}
		if(!jsonObject.get("classCode").isJsonNull()) {
			department.setClassCode(jsonObject.get("classCode").getAsString());
		}
		if(!jsonObject.get("code").isJsonNull()) {
			department.setCode(jsonObject.get("code").getAsString());
		}
		if(!jsonObject.get("parentCode").isJsonNull()) {
			department.setParentcode(jsonObject.get("parentCode").getAsString());
		}
		if(!jsonObject.get("orgCode").isJsonNull()) {
			department.setOrgCode(jsonObject.get("orgCode").getAsString());
		}
		if(!jsonObject.get("orgName").isJsonNull()) {
			department.setOrgName(jsonObject.get("orgName").getAsString());
		}
		return department;
	}
	
	private StaffBean newStaff(JsonElement jsonElement) {
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		StaffBean staff = new StaffBean();
		if(!jsonObject.get("loginName").isJsonNull()) {
			staff.setLoginid(jsonObject.get("loginName").getAsString());
		}
		/*if(!jsonObject.get("orgDepartments").isJsonNull()) {
			staff.setDepartmentCode(jsonObject.get("orgDepartmentCode").getAsString());
		}
		if(!jsonObject.get("orgDepartmentName").isJsonNull()) {
			staff.setDepartmentName(jsonObject.get("orgDepartmentName").getAsString());
		}*/
		/*if(!jsonObject.get("orgCode").isJsonNull()) {
			staff.setOrgCode(jsonObject.get("orgCode").getAsString());
		}
		if(!jsonObject.get("orgName").isJsonNull()) {
			staff.setOrgName(jsonObject.get("orgName").getAsString());
		}*/
		if(!jsonObject.get("email").isJsonNull()) {
			staff.setEmail(jsonObject.get("email").getAsString());
		}
		if(!jsonObject.get("idCard").isJsonNull()) {
			staff.setIdcard(jsonObject.get("idCard").getAsString());
		}
		if(!jsonObject.get("code").isJsonNull()) {
			staff.setCode(jsonObject.get("code").getAsString());
		}
		if(!jsonObject.get("name").isJsonNull()) {
			staff.setName(jsonObject.get("name").getAsString());
		}
		if(!jsonObject.get("mobile").isJsonNull()) {
			staff.setMobile(jsonObject.get("mobile").getAsString());
		}
		if(!jsonObject.get("phone").isJsonNull()) {
			staff.setPhone(jsonObject.get("phone").getAsString());
		}
		if(!jsonObject.get("sort").isJsonNull()) {
			staff.setWeight(jsonObject.get("sort").getAsInt());
		}
		if(!jsonObject.get("status").isJsonNull()) {
			staff.setStatus(jsonObject.get("status").getAsInt() == 1 ? 0 : 1);
		}
		return staff;
	}

}
